package pl.mchaniewski.ryneczek.web.user;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import pl.mchaniewski.ryneczek.pojo.Order;
import pl.mchaniewski.ryneczek.services.OrderService;
import pl.mchaniewski.ryneczek.utilities.FacesMessageUtil;
import pl.mchaniewski.ryneczek.utilities.I18nUtil;
import pl.mchaniewski.ryneczek.utilities.NavigationUtil;
import pl.mchaniewski.ryneczek.web.FormButton;

@Component
@Scope("request")
@PreAuthorize("isAuthenticated()")
public class ActiveOrdersListBean extends FormButton {
    private static final Logger logger = LoggerFactory
            .getLogger(ActiveOrdersListBean.class);
    private SelectedPortfolioBean selectedPortfolioBean;
    private OrderService orderService;

    /* PostConstruct parameters */
    private List<Order> orders;

    @Autowired
    public void setSelectedPortfolioBean(
            SelectedPortfolioBean selectedPortfolioBean) {
        this.selectedPortfolioBean = selectedPortfolioBean;
    }

    @Autowired
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    public List<Order> getOrders() {
        return orders;
    }

    @PostConstruct
    public void init() {
        if (selectedPortfolioBean.getSelectedPortfolioId() == null) {
            NavigationUtil.directRedirect(NavigationUtil.DIRECT_INDEX);
        }

        updateOrderList();
    }

    private void updateOrderList() {
        orders = orderService.findByPortfolioIdAndStatus(
                selectedPortfolioBean.getSelectedPortfolioId(),
                Order.STATUS_ACCEPTED);
    }

    public String cancelOrder(Order cancelOrder) {
        if (cancelOrder == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Order not selected.");
            }

            FacesMessageUtil.addMessage(getButton(), I18nUtil
                    .getLocalizedMessage("cancelorderbean.wrongOrderId"),
                    FacesMessage.SEVERITY_ERROR);

            return NavigationUtil.SAME_PAGE;
        }

        if (!orders.contains(cancelOrder)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Order list doesn't contain order with ID {}.",
                        cancelOrder.getOrderid());
            }

            FacesMessageUtil.addMessage(getButton(),
                    I18nUtil.getLocalizedMessage("cancelorderbean.cantCancel"),
                    FacesMessage.SEVERITY_ERROR);

            return NavigationUtil.SAME_PAGE;
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Selected order id {} and comapny name {}",
                    cancelOrder.getOrderid(), cancelOrder.getCompany()
                            .getName());
        }

        if (!cancelOrder.getStatus().equals(Order.STATUS_ACCEPTED)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Can't cancel order with status other than {}.",
                        Order.STATUS_ACCEPTED);
            }

            FacesMessageUtil.addMessage(getButton(),
                    I18nUtil.getLocalizedMessage("cancelorderbean.cantCancel"),
                    FacesMessage.SEVERITY_ERROR);

            return NavigationUtil.SAME_PAGE;
        }

        cancelOrder.setStatus(Order.STATUS_CANCELED);
        if (logger.isDebugEnabled()) {
            logger.debug("Order status changed to {}", Order.STATUS_CANCELED);
        }

        if (orderService.save(cancelOrder) != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Order saved successfully. Comapny name: {}",
                        cancelOrder.getCompany().getName());
            }

            updateOrderList();

            FacesMessageUtil.addMessage(getButton(),
                    I18nUtil.getLocalizedMessage("cancelorderbean.success"),
                    FacesMessage.SEVERITY_INFO);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Couldn't save order. Service returned null.");
            }

            FacesMessageUtil.addMessage(getButton(),
                    I18nUtil.getLocalizedMessage("cancelorderbean.error"),
                    FacesMessage.SEVERITY_ERROR);
        }

        return NavigationUtil.SAME_PAGE;
    }

}
